/**
 * Copyright 2009 by Christian Scheid. This file is part of the switch eclipse plugin and is licensed under the
 * GPL version 3. Please refer to the URL http://www.gnu.org/licenses/gpl-3.0.html for details.
 */
package org.digitalsoul.switchplugin.prefs;

import org.digitalsoul.switchplugin.prefs.wizards.ItemsWizard;

import org.digitalsoul.switchplugin.model.SwitchSet;
import org.digitalsoul.switchplugin.prefs.util.SetConfigurator;
import org.digitalsoul.switchplugin.prefs.util.UITools;
import org.digitalsoul.switchplugin.prefs.wizards.NewSetWizard;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.Listener;

import java.util.ArrayList;

public class SwitchSetListUI {

    protected SetConfigurator configurator;
    private List list;
    private Button newButton;
    private Button editButton;
    private Button activateButton;
    private Button removeButton;
    private Button importButton;
    private Button exportButton;

    public SwitchSetListUI(final SetConfigurator configurator) {
        this.configurator = configurator;
    }

    public void build(Composite mainPanel) {
        buildLabels(mainPanel);
        buildListView(mainPanel);
        refreshListItems();
        if (list.getItemCount() > 0) {
            list.select(0);
        }
        updateButtons();
    }

    private void buildLabels(Composite mainPanel) {
        Label label = new Label(mainPanel, SWT.NONE);
        label.setLayoutData(UITools.getTwoSpanGridData());
        label.setText(getHeader());
    }

    private void buildListView(final Composite mainPanel) {
        list = new List(mainPanel, SWT.BORDER | SWT.SINGLE | SWT.V_SCROLL);
        GridData data = new GridData(GridData.FILL_BOTH);
        data.minimumHeight = 100;
        list.setLayoutData(data);
        
        list.addListener(SWT.Selection, new Listener() {
            public void handleEvent(Event arg0) {
                itemSelectionChanged();
            }
        });
        Composite buttonPanel = new Composite(mainPanel, SWT.NONE);
        buttonPanel.setLayout(new GridLayout());
        data = new GridData();
        data.verticalAlignment = GridData.BEGINNING;
        buttonPanel.setLayoutData(data);

        // NEW...
        newButton = UITools.addButton(buttonPanel, "New...");
        newButton.addListener(SWT.Selection, new NewButtonListener(this));

        // EDIT...
        editButton = UITools.addButton(buttonPanel, "Edit");
        editButton.addListener(SWT.Selection, new Listener() {
            public void handleEvent(Event arg0) {
                UITools.openWizard(new ItemsWizard(configurator.findSet(getCurrentListItem())));
            }
        });

        // ACTIVATE
        activateButton = UITools.addButton(buttonPanel, "Activate");
        activateButton.addListener(SWT.Selection, new Listener() {
            public void handleEvent(Event event) {
                configurator.setActiveItem(getCurrentListItem());
                updateButtons();
            }
        });

        // REMOVE  
        removeButton = UITools.addButton(buttonPanel, "Remove");
        removeButton.addListener(SWT.Selection, new Listener() {
            public void handleEvent(Event event) {
                int index = list.getSelectionIndex();
                configurator.removeItem(index, getCurrentListItem());
                refreshListItems();
                UITools.selectListAfterRemove(list, index);
                updateButtons();
            }
        });

        // EXPORT
        exportButton = UITools.addButton(buttonPanel, "Export...");
        exportButton.addListener(SWT.Selection, new Listener() {
            public void handleEvent(Event event) {
                FileDialog dialog = getFileDialog(mainPanel, SWT.SAVE, "Export...");
                dialog.setFileName(getCurrentListItem() + "_switchset.xml");
                String path = dialog.open();
                if (path != null && path.trim().length() > 0) {
                    configurator.exportSet(getCurrentListItem(), path);
                }
            }
        });
        
        // IMPORT
        importButton = UITools.addButton(buttonPanel, "Import...");
        importButton.addListener(SWT.Selection, new Listener() {
            public void handleEvent(Event event) {
                FileDialog dialog = getFileDialog(mainPanel, SWT.OPEN, "Import");
                String path = dialog.open();
                if (path != null && path.trim().length() > 0) {
                    if (configurator.importSet(path)) {;
                        refreshListItems();
                        selectLastItem();
                    }
                }
            }
        });
    }
    
    private String getCurrentListItem() {
        return list.getItem(list.getSelectionIndex());
    }

    private FileDialog getFileDialog(Composite parent, int mode, String text) {
        FileDialog dialog = new FileDialog(parent.getShell(), mode);
        dialog.setText(text);
        String[] filterExt = { "*.xml", "*.XML" };
        dialog.setFilterExtensions(filterExt);
        return dialog;
    }

    public void refreshListItems() {
        list.removeAll();
        String[] listItems = getListItems();
        boolean modelHasSet = listItems != null && listItems.length > 0;
        if (modelHasSet) {
            list.setItems(listItems);
        }
        list.setEnabled(modelHasSet);
        list.update();
    }

    private void updateButtons() {
        activateButton.setEnabled(listHasSelection() && !configurator.isActiveSet(getCurrentListItem()));
        exportButton.setEnabled(listHasSelection());
        removeButton.setEnabled(listHasSelection());
        editButton.setEnabled(listHasSelection());
    }

    private boolean listHasSelection() {
        return list.getSelectionIndex() >= 0;
    }

    public void itemSelectionChanged() {
        updateButtons();
    }

    private String[] getListItems() {
        java.util.List<String> itemNames = new ArrayList<String>();
        for (SwitchSet set : configurator.getSets()) {
            itemNames.add(set.getName());
        }
        return itemNames.toArray(new String[itemNames.size()]);
    }

    private String getHeader() {
        return "Switch Sets";
    }

    private final class NewButtonListener implements Listener {
        private final SwitchSetListUI setListUI;

        public NewButtonListener(SwitchSetListUI setListUI) {
            this.setListUI = setListUI;
        }

        public void handleEvent(Event event) {
            UITools.openWizard(new NewSetWizard(setListUI, configurator));
        }
    }

    public void selectLastItem() {
        list.select(list.getItemCount()-1);
        updateButtons();
    }
}
